<%--
  Created by IntelliJ IDEA.
  User: humeng
  Date: 2022/11/21
  Time: 15:15
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>index</title>
    <link rel="stylesheet" href="./bootstrap-3.4.1-dist/css/bootstrap.min.css">
</head>
<body>
<div class="container">
    <div class="row">
        <h1>首页</h1>
    </div>
    <div class="row">
        <form action="upload" method="post" id="f1" enctype="multipart/form-data">
            <div class="col-xs-3">
                <input type="file" name="f1" id="fi" multiple>
            </div>
            <div class="col-xs-3">
                <input type="submit"  value="上传图片" class="btn btn-primary">
            </div>
        </form>
    </div>
    <div class="row">
        <img id="showImg"  class="img-rounded img-responsive" width="240">
    </div>

</div>

<script>
    const f1 = document.querySelector('#f1')
    const img = document.querySelector('#showImg')

    f1.addEventListener('submit',function (e){
        e.preventDefault()
        const file = document.querySelector('#fi').files
        const fd = new FormData(f1)
        console.log(file)
        if (file.length===0){
            alert("请选择文件")
            return
        }
        const xhr = new XMLHttpRequest()
        xhr.open("post","/upload")
        xhr.send(fd)

        xhr.onreadystatechange = function (){
            if(xhr.readyState === 4){
                if (xhr.status>=200&&xhr.status<300){
                    const data = JSON.parse(xhr.responseText)
                    // console.log(data)
                    let index = data.data.lastIndexOf("/")
                    let imgSrc = data.data.substring(index+1)
                    // console.log(imgSrc)
                    img.src = "/images/"+imgSrc
                    // alert("上传成功")

                }else {
                    alert("上传失败")
                }
            }
        }

    })
</script>
</body>
</html>
